package com.example.dynamic_form.controller;

import com.example.dynamic_form.domain.po.UserPo;
import com.example.dynamic_form.service.IUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.util.List;

@RestController
@RequestMapping("hello")
@Slf4j
public class HelloController {
    @Resource
    private IUserService userService;

    @PostMapping("createUser")
    public UserPo helloPost(@RequestBody UserPo userInfo) {
        log.info("User info is:{}", userInfo);
        userService.save(userInfo);
        return userInfo;
    }


    @GetMapping("listUser")
    public List<UserPo> listUser() {
        return userService.list();
    }

    @PostMapping("deleteUser")
    public Boolean deleteUser(@RequestParam(required = true) Long id) {
        return userService.removeById(id);
    }

    @PostMapping("updateUser")
    public Object updateUser(@RequestBody UserPo userInfo) {
        userService.updateById(userInfo);
        return userInfo;
    }

    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
        // 指定要返回的文件
        File file = new File("C:\\Users\\Administrator\\Downloads\\test.txt");

        // 创建文件输入流
        FileInputStream fileInputStream = new FileInputStream(file);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE + ";charset=utf-8");

        // 返回文件流
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
//                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new InputStreamResource(fileInputStream));
    }
}
